#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/of.h>

#define BUF_SIZE (1024 * 4) // 4KB DMA缓冲区的大小

static void *buf;
static dma_addr_t dma_handle;

static int my_probe(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;

    //分配DMA缓冲区
    buf = dma_alloc_coherent(dev, BUF_SIZE, &dma_handle, GFP_KERNEL);
    if (!buf) {
        dev_err(dev, "Failed to allocate source buffer\n");
        return -ENOMEM;
    }

    return 0;
}

static int my_remove(struct platform_device *pdev)
{
    struct device *dev = &pdev->dev;

    // 将DMA缓冲区从物理地址取消映射
    dma_free_coherent(dev, BUF_SIZE, buf, dma_handle);

    return 0;
}

static const struct of_device_id my_of_match[] = {
    { .compatible = "my-dma-test", },
    {},
};
MODULE_DEVICE_TABLE(of, my_of_match);

static struct platform_driver my_driver = {
    .probe = my_probe,
    .remove = my_remove,
    .driver = {
        .name = "my-dma-test",
        .owner = THIS_MODULE,
        .of_match_table = of_match_ptr(my_of_match),
    },
};

module_platform_driver(my_driver);
MODULE_LICENSE("GPL");
